<template>
  <!-- 卡片盒子 -->
  <el-card class="box-card">
    <!-- 1.头部插槽 -->
    <div slot="header" class="clearfix">
      <span>更换头像</span>
    </div>
    <!-- 2.内容盒子 -->
    <div>
      <!-- 图片，用来展示用户选择的头像 -->
      <img :src="avatar" alt="" class="preview" v-if="avatar" />
      <img src="@/assets/images/avatar.jpg" alt="" class="preview" v-else />

      <!-- 按钮区域 -->
      <div class="btn-box">
        <!-- 渲染一个被隐藏的文件选择框，只允许选中图片文件 -->
        <input
          type="file"
          style="display: none"
          accept="image/*"
          ref="iptRef"
          @change="onFileChange"
        />
        <el-button
          type="primary"
          icon="el-icon-plus"
          @click="$refs.iptRef.click()"
          >选择图片</el-button
        >
        <el-button
          :disabled="avatar === ''"
          type="success"
          icon="el-icon-upload"
          @click="uploadAvatar"
          >上传头像
        </el-button>
      </div>
    </div>
  </el-card>
</template>

<script>
export default {
  name: "UserAvatar",
  data() {
    return {
      //用户头像  base64字符串
      avatar: "",
    };
  },
  methods: {
    //1.头像预览
    onFileChange(e) {
      //(1)获取用户选择的文件
      // let file=this.$refs.iptRef.files[0]
      let file = e.target.files[0];
      console.log(file);
      console.log(e);
      //(2)内置对象的FileReader读取文件
      const fr = new FileReader();
      //开始异步读取文件数据
      fr.readAsDataURL(file);
      //(3)注册读取成功回调
      fr.onload = (e) => {
        console.log(e); //读取成功之后的事件对象
        //读取的base64绑定到data
        this.avatar = e.target.result;
      };
    },
    //2.头像提交
    async uploadAvatar() {
      //（1）发送ajax
      const { data: res } = await this.$axios.patch("/my/update/avatar", {
        avatar: this.avatar,
      });
      console.log(res);
      this.$message.success(res.message)
      //(2)成功之后，更新到vuex
      if (res.code===0) {
        
        //提交到vuex
        this.$store.dispatch('getUserInfo')
        this.avatat=''
      }
    },
  },
};
</script>

<style lang="less" scoped>
.btn-box {
  margin-top: 10px;
}
.preview {
  object-fit: cover;
  width: 350px;
  height: 350px;
}
</style>
